<template>
    <view style="height: 100%">
        <!-- marketing/pages/promotion/apply/apply.wxml -->
        <form @submit="submit">
            <view class="apply_wrap">
                <view class="desc">请填写真实信息，提交后需等待工作人员审核</view>

                <view class="apply_form">
                    <view class="form_item flex-row-start" v-if="rules.plUserName && rules.plUserName.isNeed != 3">
                        <view class="item_title flex-row-start">
                            <text v-if="rules.plUserName.isNeed === 1">*</text>
                            姓名
                        </view>
                        <input v-model="form.plUserName" class="item_input flex_1" name="plUserName" placeholder="请输入姓名" type="text" />
                    </view>
                    <view class="form_item flex-row-start" v-if="rules.plUserPhone && rules.plUserPhone.isNeed != 3">
                        <view class="item_title flex-row-start">
                            <text v-if="rules.plUserPhone.isNeed === 1">*</text>
                            手机号码
                        </view>
                        <input v-model="form.plUserPhone" name="plUserPhone" class="item_input flex_1" placeholder="请输入手机号码" type="number" />
                    </view>
					
                					
					<!-- #ifndef MP-WEIXIN -->
					<view class="form_item flex-row-start" v-if="rules.areaName && rules.areaName.isNeed != 3" @click='openPicker'>
					    <view class="item_title flex-row-start">
					        <text v-if="rules.areaName.isNeed === 1">*</text>
					        推广地区
					    </view>
						<input class="item_input flex_1" v-model="form.areaName" disabled name="areaName" placeholder="请选择推广地区" type="text" style="pointer-events:none" />					
					    <view class="arrows_r"></view>
					</view>
					<!-- #endif -->
					
					<!-- #ifdef MP-WEIXIN -->
					<view class="form_item flex-row-start" v-if="rules.areaName && rules.areaName.isNeed != 3" >
					    <view class="item_title flex-row-start">
					        <text v-if="rules.areaName.isNeed === 1">*</text>
					        推广地区
					    </view>
							<picker v-if="envVersion == 'develop'" class="item_input flex_1" mode='region' @change="bindRegionChange" v-model="region">
							    <input class="item_input flex_1" v-model="form.areaName" disabled name="areaName" placeholder="请选择推广地区" type="text" />
							</picker>
							<picker v-else  class="item_input flex_1" mode='region' @change="bindRegionChange" v-model="region" level="sub-district">
							    <input class="item_input flex_1" v-model="form.areaName" disabled name="areaName" placeholder="请选择推广地区" type="text" />
							</picker>
					    <view class="arrows_r"></view>
					</view>
					<!-- #endif -->
					
					
					
					
					
					
					
                    <view class="form_item flex-row-start" v-if="rules.applyCreditNo && rules.applyCreditNo.isNeed != 3">
                        <view class="item_title flex-row-start">
                            <text v-if="rules.applyCreditNo.isNeed === 1">*</text>
                            身份证号码
                        </view>
                        <input v-model="form.applyCreditNo" name="applyCreditNo" class="item_input flex_1" placeholder="请输入身份证号码" type="idcard" />
                    </view>

                    <view class="upload_wrap flex-row-start flex_wrap" v-if="rules.applyCreditPicUrl && (rules.applyCreditPicUrl.isNeed != 3 || rules.applyUserPicUrl.isNeed != 3)">
                        <view class="upload_item flex-row-center" v-if="rules.applyCreditPicUrl && rules.applyCreditPicUrl.isNeed != 3">
                            <image
                                class="img"
                                src="https://oos-cn.ctyunapi.cn/front-end/static/marketingImg/marketing/images/ids1.png"
                                v-if="applyCreditPicUrl.length == '0'"
                            ></image>
                            <view class="flex-column-start">
								<u-upload
										name="applyCreditPicUrl"
										@afterRead="afterRead"
										accept="image"
										:maxCount="1"
										:deletable="true"
										:fileList="applyCreditPicUrl"
										@delete="deleteFun"
									>
										<!-- <van-button icon="photo" type="primary"> -->
										    <image src="https://oos-cn.ctyunapi.cn/front-end/static/marketingImg/marketing/images/update.png" class="update"></image>
										<!-- </van-button> -->
									</u-upload>
                                <view class="up_text" v-if="applyCreditPicUrl.length === 0">上传身份证正面</view>
                            </view>
                        </view>

                        <view class="upload_item flex-row-center" v-if="rules.applyCreditPicUrl && rules.applyCreditPicUrl.isNeed != 3">
                            <image
                                class="img"
                                src="https://oos-cn.ctyunapi.cn/front-end/static/marketingImg/marketing/images/ids0.png"
                                v-if="applyCreditBackPicUrl.length == 0"
                            ></image>
                            <view class="flex-column-start">
								<u-upload
										name="applyCreditBackPicUrl"
										@afterRead="afterRead"
										accept="image"
										:maxCount="1"
										:deletable="true"
										:fileList="applyCreditBackPicUrl"
										@delete="deleteFun"
									>
										<!-- <van-button icon="photo" type="primary"> -->
										    <image src="https://oos-cn.ctyunapi.cn/front-end/static/marketingImg/marketing/images/update.png" class="update"></image>
										<!-- </van-button> -->
									</u-upload>
									
                                <!-- <van-uploader
                                    name="applyCreditBackPicUrl"
                                    @after-read="afterRead"
                                    accept="image"
                                    max-count="1"
                                    :deletable="true"
                                    :file-list="applyCreditBackPicUrl"
                                    @delete="deleteFun"
                                >
                                    <van-button icon="photo" type="primary">
                                        <image src="https://oos-cn.ctyunapi.cn/front-end/static/marketingImg/marketing/images/update.png" class="update"></image>
                                    </van-button>
                                </van-uploader> -->
                                <view class="up_text" v-if="applyCreditBackPicUrl.length == 0">上传身份证反面</view>
                            </view>
                        </view>

                        <view class="upload_item flex-row-center" v-if="rules.applyUserPicUrl && rules.applyUserPicUrl.isNeed != 3">
                            <!-- <image src="https://oos-cn.ctyunapi.cn/front-end/static/marketingImg/marketing/images/delete.png" class="delete"></image> -->
                            <!-- <image class="img" src="https://oos-cn.ctyunapi.cn/front-end/static/marketingImg/marketing/images/ids'0'.png"></image> -->
                            <view class="flex-column-start">
								
								<u-upload
										name="applyUserPicUrl"
										@afterRead="afterRead"
										accept="image"
										:maxCount="1"
										:deletable="true"
										:fileList="applyUserPicUrl"
										@delete="deleteFun"
									>
										<!-- <van-button icon="photo" type="primary"> -->
										    <image src="https://oos-cn.ctyunapi.cn/front-end/static/marketingImg/marketing/images/update.png" class="update"></image>
										<!-- </van-button> -->
									</u-upload>
									
                                <view class="up_text" v-if="applyUserPicUrl.length == '0'">上传个人照片</view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <view class="btn_wrap flex-row-center">
                <button class="btn flex-row-center" type="primary" formType="submit">提交审核</button>
            </view>
        </form>
		
		<!-- #ifndef MP-WEIXIN-->
		<u-popup :show="showPopup" @close="closePopup" mode="bottom">
			<erha-picker @conceal="conceal"></erha-picker>
		</u-popup>
		<!-- #endif -->
    </view>
</template>
<script>

var promotion_1 = require("../../../../api/marketing/promotion");
// #ifndef MP-WEIXIN
import erhaPicker from '../../../components/erha-picker/index';
// #endif
export default {
	components:{
		// #ifndef MP-WEIXIN
		erhaPicker,
		// #endif
	},
    data() {
        return {
			showPopup:false,
			// region:'',
            envVersion: getApp().getEnvVersion(),
            region: [],
            level: 'region',
            customItem: '全部',
            plUserName: undefined,
            form: {
                plUserName: undefined,
                plUserPhone: Number(uni.getStorageSync('tel')),
                areaName: undefined,
                applyCreditNo: undefined,
                applyUserPicUrl: undefined,
                applyCreditPicUrl: undefined,
                applyCreditBackPicUrl: undefined
            },
            rules: {
                plUserName: {
                    message: '请输入申请人名称！',
                    isNeed: 0
                },
                plUserPhone: {
                    message: '请输入正确的手机号！',
            
                    // pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
                    pattern: 'phone',
            
                    isNeed: 0
                },
            
                areaName: {
                    message: '请输入推广地区！',
                    isNeed: 0
                },
                applyCreditNo: {
                    message: '请输入正确的身份证号！',
            
                    // pattern: /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/
                    pattern: 'IdNum',
            
                    isNeed: 0
                },
            
                applyUserPicUrl: {
                    message: '请上传个人照片！',
                    isNeed: 0
                },
                applyCreditPicUrl: {
                    message: '请上传身份证正面照片！',
                    isNeed: 0
                },
                applyCreditBackPicUrl: {
                    message: '请上传身份证反面照片！'
                }
            },
            applyUserPicUrl: [],
            applyCreditPicUrl: [],
            applyCreditBackPicUrl: []
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
			// // #ifdef  MP-WEIXIN
			// this.setData({
			// 	envVersion:wx.getAccountInfoSync().miniProgram.envVersion
			// })
			// // #endif
		this.getConfigPage();
		
		// 重新申请
		const applyAgainInfo = uni.getStorageSync('applyAgainInfo');
		if (applyAgainInfo) {
		    const { plUserName, plUserPhone, areaName } = JSON.parse(applyAgainInfo);
		    this.setData({
		        'form.plUserName': plUserName,
		        'form.plUserPhone': plUserPhone,
		        'form.areaName': areaName
		    });
		    uni.setStorageSync('applyAgainInfo', '');
		}
    },
    methods: {
		closePopup(){
			this.showPopup = false
		},
		conceal(res){
			console.log(res)
			this.region = [res.province,res.city,res.area,res.street];
			this.form.areaName = [...this.region]
			this.showPopup = false;
		},
		openPicker() {
			this.showPopup = true;
		},
        bindRegionChange: function (e) {
            console.log('picker发送选择改变，携带值为', e.detail.value);
            this.setData({
                'form.areaName': e.detail.value
            });
        },
        
        // 校验表单
        validate(data, rules) {
            let result = false;
            for (let item in rules) {
                if (rules[item].required && !data[item]) {
                    uni.showToast({
                        title: rules[item].message,
                        icon: 'none',
                        duration: 2000
                    });
                    result = false;
                    break;
                }
                if (rules[item].pattern && data[item]) {
                    let reg;
                    switch (rules[item].pattern) {
                        case 'phone':
                            reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
                            break;
                        case 'IdNum':
                            reg = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/;
                            break;
                    }
                    if (!reg.test(data[item])) {
                        uni.showToast({
                            title: rules[item].message,
                            icon: 'none',
                            duration: 2000
                        });
                        result = false;
                        break;
                    }
                }
                result = true;
            }
            return result;
        },
        
        async submit(e) {
            const _params = {
                // ...this.data.form,
                ...e.detail.value,
                applyChannel: 1,
                plUserId: uni.getStorageSync('memberId'),
                applyUserPicUrl: (this.applyUserPicUrl[0])?.url,
                applyCreditPicUrl: (this.applyCreditPicUrl[0])?.url,
                applyCreditBackPicUrl: (this.applyCreditBackPicUrl[0])?.url
            };
            if (this.validate(_params, this.rules)) {
                const { code } = await promotion_1.applyPost(_params);
                if (code === 200) {
                    uni.setStorageSync('applySuccess', true);
                    uni.navigateBack({
				delta: 1,
			  }); 
                }
            }
        },
        
        async getConfigPage() {
            const { code, data } = await promotion_1.getParamsConfig();
            if (code === 200) {
                const rules = {};
                const keyOjb = {
                    申请人名称: 'plUserName',
                    申请人手机: 'plUserPhone',
                    申请人地区: 'areaName',
                    身份证号码: 'applyCreditNo',
                    个人照片: 'applyUserPicUrl',
                    身份证照片: 'applyCreditPicUrl'
                };
                data.forEach((item) => {
                    rules[keyOjb[item.columnName]] = {
                        ...this.rules[keyOjb[item.columnName]],
                        required: item.isNeeded === 1,
                        isNeed: item.isNeeded // 1：展示且必填；2：展示非必填；3：不展示
                    };
                });
        
                rules.applyCreditBackPicUrl = {
                    ...this.rules.applyCreditPicUrl,
                    ...this.rules.applyCreditBackPicUrl
                };
                this.setData({
                    rules: rules
                });
            }
        },
        
        // 文件上传
        afterRead(event) {
			console.log(event,'lllsss')
            const { file, name } = event;
            // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
            const _this = this;
            uni.showLoading({
                title: '上传中'
            });
            uni.uploadFile({
                url: `${uni.getStorageSync('imgUrl')}/api/member-service/common/upload`,
                filePath: file.url,
                name: 'file',
                formData: {
                    user: 'test'
                },
                success(res) {
                    if (res.statusCode != 200) {
                        uni.hideLoading();
                        uni.showToast({
                            title: '上传的图片过大',
                            icon: 'none',
                            duration: 2000
                        });
                        return;
                    }
                    const { code, data } = JSON.parse(res.data);
                    if (code === 0) {
                        const urlInfo = [
                            {
                                ...file,
                                url: data
                            }
                        ];
                        const obj = {};
                        obj[name] = urlInfo;
                        uni.hideLoading();
                        _this.setData(obj);
                    } else {
                        uni.showToast({
                            title: '上传的图片过大',
                            icon: 'none',
                            duration: 2000
                        });
                    }
                },
                fail(err) {
					console.log(err,'失败原因')
                    uni.hideLoading();
                    uni.showToast({
                        title: '上传失败',
                        icon: 'none',
                        duration: 2000
                    });
                }
            });
        },
        
        deleteFun(e) {
            const { name } = e;
            const obj = {};
            obj[name] = [];
            this.setData(obj);
        }
        
    }
};
</script>
<style lang="less" scoped>
	@import "../../../../commin/flex.less";
/* marketing/pages/promotion/apply/apply.wxss */
/*数字*/
/*固定布局*/
/*宽高*/
/* 行高 */
/* 外边距 */
/* 实边框 */
/* 定位  */
.record-in .aaa1 {
    color: #909399;
}
.record-in .aaa2 {
    color: #1487fa;
}
.record-in .aaa3 {
    color: #f7a14a;
}
.record-in .aaa4 {
    color: #72c23d;
}
.record-in .aaa5 {
    color: #606266;
}
page {
    background-color: #f5f7fa;
}
.arrows_r {
    width: 16rpx;
    height: 16rpx;
    border-top: 1px solid #5a3e3e;
    border-right: 1px solid #5a3e3e;
    transform: rotate(45deg);
}
.apply_wrap {
    padding: 40rpx 24rpx;
}
.apply_wrap .desc {
    font-size: 26rpx;
    color: #303133;
    margin-bottom: 24rpx;
}
.apply_form {
    background: linear-gradient(0deg, #ffffff, #f4f6f8);
    border: 2rpx solid #ffffff;
    box-shadow: 4rpx 7rpx 20rpx 0px rgba(166, 171, 179, 0.24);
    border-radius: 16rpx;
    padding: 0 32rpx;
    font-size: 28rpx;
}
.apply_form .form_item {
    height: 111rpx;
    border-bottom: 1rpx solid #dcdfe6;
}
.apply_form .form_item .picker {
    height: 100rpx;
    width: 100%;
}
.apply_form .item_title {
    width: 220rpx;
}
.apply_form .item_title text {
    color: #fc724c;
}
.apply_form .upload_wrap {
    padding: 35rpx 0;
}
.apply_form .upload_wrap .update {
    width: 72rpx;
    height: 72rpx;
}
.apply_form .upload_wrap .up_text {
    font-size: 24rpx;
    color: #606266;
    margin-top: 10rpx;
}
.apply_form .upload_wrap .upload_item {
    width: 306rpx;
    margin-right: 14rpx;
    height: 190rpx;
    margin-bottom: 14rpx;
    position: relative;
    border: 1rpx dashed #e2e6ed;
    border-radius: 12rpx;
    z-index: 1;
}
.apply_form .upload_wrap .upload_item .delete {
    width: 29rpx;
    height: 29rpx;
    right: 0;
    top: 0;
    position: absolute;
}
.apply_form .upload_wrap .upload_item:nth-child(2) {
    margin-right: 0;
}
.apply_form .upload_wrap .upload_item .img {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: -1;
    filter: blur(2px);
}
.btn_wrap {
    width: 100%;
    height: 120rpx;
    background: #ffffff;
    position: fixed;
    bottom: 0;
    left: 0;
}
.btn_wrap .btn {
    width: 686rpx;
    height: 88rpx;
    background: linear-gradient(105deg, #268ae8, #1487fa);
    box-shadow: 0px 3rpx 6rpx 0rpx rgba(0, 110, 212, 0.3);
    border-radius: 44rpx;
    font-size: 30rpx;
    font-weight: bold;
    color: #ffffff;
}
</style>
